/*
 * Mediana.cpp
 *
 *  Created on: Dec 7, 2009
 *      Author: tptfc
 */

#include "Mediana.h"
#include <math.h>

Mediana::Mediana() {
}

Mediana::~Mediana() {
}

void Mediana::applyFilterInVector(int width, int height, int **vectors, int **newVectors) {
	if (vectors != NULL && newVectors != NULL) {
		#pragma omp parallel for default(shared)
		for (int i = 0; i < height; i++) {
			#pragma omp parallel for default(shared)
			for (int j = 0; j < width; j++) {
				int centerValue = vectors[i][j];
				int upLeftValue = getUpLeftValue(i, j, width, height, vectors);
				int upCenterValue = getUpCenterValue(i, j, width, height, vectors);
				int upRightValue = getUpRightValue(i, j, width, height, vectors);
				int centerLeftValue = getCenterLeftValue(i, j, width, height, vectors);
				int centerRightValue = getCenterRightValue(i, j, width, height, vectors);
				int downLeftValue = getDownLeftValue(i, j, width, height, vectors);
				int downCenterValue = getDownCenterValue(i, j, width, height, vectors);
				int downRightValue = getDownRightValue(i, j, width, height, vectors);

				double calculatedValue = centerValue;
				calculatedValue += upLeftValue;
				calculatedValue += upCenterValue;
				calculatedValue += upRightValue;
				calculatedValue += centerLeftValue;
				calculatedValue += centerRightValue;
				calculatedValue += downLeftValue;
				calculatedValue += downCenterValue;
				calculatedValue += downRightValue;
				calculatedValue /= 9;

				int newValue = centerValue;
				int distance = pow(centerValue - calculatedValue, 2);

				int upLeftDistance = (pow(upLeftValue - calculatedValue, 2));
				if (upLeftDistance < distance) {
					newValue = upLeftValue;
				}

				int upCenterDistance = (pow(upCenterValue - calculatedValue, 2));
				if (upCenterDistance < distance) {
					newValue = upCenterValue;
				}

				int upRightDistance = (pow(upRightValue - calculatedValue, 2));
				if (upRightDistance < distance) {
					newValue = upRightValue;
				}

				int centerLeftDistance = (pow(centerLeftValue - calculatedValue, 2));
				if (centerLeftDistance < distance) {
					newValue = centerLeftValue;
				}

				int centerRightDistance = (pow(centerRightValue - calculatedValue, 2));
				if (centerRightDistance < distance) {
					newValue = centerRightValue;
				}

				int downLeftDistance = (pow(downLeftValue - calculatedValue, 2));
				if (downLeftDistance < distance) {
					newValue = downLeftValue;
				}

				int downCenterDistance = (pow(downCenterValue - calculatedValue, 2));
				if (downCenterDistance < distance) {
					newValue = downCenterValue;
				}

				int downRightDistance = (pow(downRightValue - calculatedValue, 2));
				if (downRightDistance < distance) {
					newValue = downRightValue;
				}

				newVectors[i][j] = newValue;
			}
		}
	}
}
